import Vue from 'vue'
import Vuex from 'vuex'
// 引入接口
import { loginApi } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  // vuex数据
  state: {
    // 判断本地有没有数据
    token: localStorage.getItem('token') || '',
    refresh_token: localStorage.getItem('refresh_token') || '',
    user: JSON.parse(localStorage.getItem('user')) || {}
  },
  // 定义修改state的数据函数
  mutations: {
    setToken (state, token) {
      state.token = token
      // 本地存储
      localStorage.setItem('token', token)
    },
    setRefreshToken (state, refreshToken) {
      state.refresh_token = refreshToken
      // 本地存储
      localStorage.setItem('refresh_token', refreshToken)
    },
    setUser (state, user) {
      state.user = user
      localStorage.setItem('user', JSON.stringify(user))
    }
  },
  // 执行异步操作 （请求）
  actions: {
    async asyncLoginApi (store, val) {
      // 第一个参数就是 new Vuex.Store对象
      try {
        const res = await loginApi(val)
        const { refresh_token: refreshToken, token } = res.data.data
        store.commit('setToken', token)
        store.commit('setRefreshToken', refreshToken)
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    }
  },
  modules: {
  }
})
